using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ImoviesBlazorAntPro.Server.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;
using System;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.Text.Json;
using ImoviesBlazorAntPro.Server.Repository;
using ImoviesBlazorAntPro.Server.Helpers;
using Newtonsoft.Json;

namespace ImoviesBlazorAntPro.Server
{
    public class Startup
    {
        public IConfiguration Configuration { get; }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews().AddNewtonsoftJson(option =>
            {
                // json时间日期格式化
                option.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                // 忽略循环引用
                option.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });
            services.AddRazorPages();

            // services.AddDbContext<ApplicationDbContext>(options =>
            //         options.UseMySql(Configuration.GetConnectionString("MySqlConnection"), new MySqlServerVersion(new Version(8, 0, 11))));

            services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlite(Configuration.GetConnectionString("SqliteConnection")));

            services.AddIdentity<IdentityUser, IdentityRole>(options =>
            //services.AddDefaultIdentity<IdentityUser>(options =>
            {
                // Password settings.
                options.Password.RequireDigit = true;
                options.Password.RequireLowercase = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
                options.Password.RequiredLength = 6;

                // Lockout settings.
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.Lockout.AllowedForNewUsers = true;

                // User settings
                options.SignIn.RequireConfirmedAccount = false; // ע�����ȷ�ϲ��ܵ�¼����Ϊ��false
                options.User.RequireUniqueEmail = false;

            }).AddEntityFrameworkStores<ApplicationDbContext>();


            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["Jwt:JwtIssuer"],
                    ValidAudience = Configuration["Jwt:JwtAudience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:JwtSecurityKey"]))
                };
            });

            // 电视剧仓储
            services.AddScoped<ITeleplayRepository, TeleplayRepository>();
            // 电影仓储
            services.AddScoped<IMovieRepository, MovieRepository>();
            // 动漫仓储
            services.AddScoped<IAnimationRepository, AnimationRepository>();
            // 年度评论仓储
            services.AddScoped<IAnnualReviewRepository, AnnualReviewRepository>();
            // 电视剧链接仓储服务
            services.AddScoped<ITeleplayVlinkRepository, TeleplayVlinkRepository>();
            // 电影链接仓储服务
            services.AddScoped<IMovieVlinkRepository, MovieVlinkRepository>();
            // 动漫链接仓储服务
            services.AddScoped<IAnimationVlinkRepository, AnimationVlinkRepository>();
            // 播放链接仓储服务
            services.AddScoped<IPlaylinkRepository, PlaylinkRepository>();

            // automapper配置
            services.AddAutoMapper(typeof(MyMappingProfile));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebAssemblyDebugging();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();

            app.UseRouting();


            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapFallbackToFile("index.html");
            });
        }
    }
}
